package org.myspringframework.core.io;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

//ClassPath 下的文件 classpath:xxx.xml
public class ClassPathResource implements Resource {

    //文件路径
    private final String path;

    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, (ClassLoader) null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        if(path==null||path==""){
            throw new RuntimeException("文件路径为空！");
        }
        this.path = path;
        this.classLoader = (classLoader != null ? classLoader : Thread.currentThread().getContextClassLoader());
    }

    //获取目标文件的输入流
    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is = classLoader.getResourceAsStream(path);
        if (is == null) {
            throw new FileNotFoundException(
                    this.path + " 不存在！");
        }
        return is;
    }
}